﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;

/// <summary>
/// ExportExcel 的摘要说明
/// </summary>
public class ExportExcel
{
    public ExportExcel()
    {
        
    }
    public static void CreateExcel(Page page, DataSet ds, string FileName,List<int> list)
    {
        HttpResponse resp;
        resp = page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
        string colHeaders = "", ls_item = "";

        for (int x = 0; x < ds.Tables.Count; x++)
        {
            DataTable dt = ds.Tables[x];
            int cols = dt.Columns.Count;
            if (list.Contains(x))
            {
                //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符 
                for (int i = 0; i < cols; i++)
                {
                    if (i == (cols - 1))//最后一列，加n
                    {
                        colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                    }
                    else
                    {
                        colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                    }

                }
                resp.Write(colHeaders);//向HTTP输出流中写入取得的数据信息 
                colHeaders = "";
            }            
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (int i = 0; i < cols; i++)
                {
                    if (i == (cols - 1))//最后一列，加n
                    {

                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                resp.Write(ls_item);
                ls_item = "";
            }
            
        }
        resp.End();
    }
}
